//
//  MyTabView.m
//  ebox
//
//  Created by hzm on 16/7/25.
//  Copyright © 2016年 BoingPay. All rights reserved.
//

#import "MyTabView.h"
#import "AppUtils.h"


static NSString *const s_tabViewCellIdentifier = @"tabViewCellIdentifier";

@interface MyTabView()<UICollectionViewDelegate, UICollectionViewDataSource, UICollectionViewDelegateFlowLayout>

@property (nonatomic, assign) CGFloat frameWidth;
@property (nonatomic, assign) NSInteger tabCount;
@property (nonatomic, retain) UIFont *font;
@property (nonatomic, retain) UIColor *selColor;
@property (nonatomic, retain) UIColor *unselColor;
@property (nonatomic, retain) NSArray *titles;
@property (nonatomic, retain) NSArray *bodyViews;
@property (nonatomic, assign) NSInteger selIndex;
@property (nonatomic, retain) NSMutableArray *tabLabels;
@property (nonatomic, retain) NSMutableArray *tabPointViews;
@property (nonatomic, retain) NSMutableArray *tabPointLabels;
@property (nonatomic, weak) id target;
@property (nonatomic, assign) SEL select;


@end

@implementation MyTabView

+ (instancetype)tabViewWithFrameView:(UIView *)view
{
    if (nil == view) {
        return nil;
    }
    MyTabView *tabView = [[[NSBundle mainBundle] loadNibNamed:@"MyTabView" owner:nil options:nil] firstObject];
    [tabView setFrame:CGRectMake(0, 0, view.width, view.height)];
    [tabView setFrameWidth:view.width];
    [tabView setRedPointOffset:0.75f];
    [tabView setShowSeperator:NO];
    [view addSubview:tabView];
    
    // constraints
    [tabView setTranslatesAutoresizingMaskIntoConstraints:NO];
    [view addConstraints:[NSLayoutConstraint constraintsWithVisualFormat:@"H:|-0-[tabView]-0-|" options:0 metrics:nil views:NSDictionaryOfVariableBindings(tabView)]];
    [view addConstraints:[NSLayoutConstraint constraintsWithVisualFormat:@"V:|-0-[tabView]-0-|" options:0 metrics:nil views:NSDictionaryOfVariableBindings(tabView)]];
    tabView.frameWidth = view.width;
    return tabView;
}

+ (instancetype)tabViewWithRect:(CGRect)rc
{
    MyTabView *tabView = [[[NSBundle mainBundle] loadNibNamed:@"MyTabView" owner:nil options:nil] firstObject];
    [tabView setFrame:rc];
    [tabView setFrameWidth:rc.size.width];
    [tabView setRedPointOffset:0.75f];
    [tabView setShowSeperator:NO];
    return tabView;
}

- (void)awakeFromNib
{
    [super awakeFromNib];

    [_collectionTypeSelect registerClass:[UICollectionViewCell class] forCellWithReuseIdentifier:s_tabViewCellIdentifier];
    _selIndex = -1;
}

- (void)setTabTitles:(NSArray *)titles font:(UIFont *)font selColor:(UIColor *)selColor unselColor:(UIColor *)unselColor
{
    if ([AppUtils isEmptyArray:titles]) {
        return;
    }
    _tabCount = [titles count];
    _titles = titles;
    _font = font;
    _selColor = selColor;
    _unselColor = unselColor;
    _consIndicatorW.constant = _frameWidth / _tabCount;
    
    _tabLabels = [[NSMutableArray alloc] init];
    _tabPointViews = [[NSMutableArray alloc] init];
    _tabPointLabels = [[NSMutableArray alloc] init];
    for (NSInteger i = 0; i < _tabCount; ++i) {
        [_tabLabels addObject:[NSNull null]];
        [_tabPointViews addObject:[NSNull null]];
        [_tabPointLabels addObject:[NSNull null]];
    }
    [_collectionTypeSelect reloadData];
}

- (void)updateFrameWidth:(CGFloat)width
{
    _frameWidth = width;
    if (_tabCount == 0) {
        _consIndicatorW.constant = _frameWidth;
    }
    else {
        _consIndicatorW.constant = _frameWidth / _tabCount;
    }
}

- (void)setTabBackgroundColor:(UIColor *)color
{
    _collectionTypeSelect.backgroundColor = color;
}

- (void)setIndicatorColor:(UIColor *)color
{
    if (nil != color) {
        [_viewIndicator setBackgroundColor:color];
    }
}

- (void)setBodyViews:(NSArray *)views
{
    _bodyViews = views;
}

- (void)selectIndex:(NSInteger)index
{
    [self selectIndex:index animated:YES];
}

- (void)selectIndex:(NSInteger)index animated:(BOOL)anim
{
    if (index < 0 || index >= _tabCount || index == _selIndex) {
        return;
    }
    NSInteger oldSelect = _selIndex;
    _selIndex = index;
    
    // view visible
    if (![AppUtils isEmptyArray:_bodyViews]) {
        for (NSInteger i = 0; i < _bodyViews.count; ++i) {
            if ([_bodyViews[i] isKindOfClass:[UIView class]]) {
                UIView *view = _bodyViews[i];
                [view setHidden:(i != index)];
            }
        }
    }
    
    // indicator position
    [_viewIndicator.layer removeAllAnimations];
    CGFloat targetX = _frameWidth / _tabCount * index;
    if (oldSelect < 0 || !anim) {
        _viewIndicator.left = targetX;
        _consIndicatorX.constant = targetX;
    }
    else {
        [UIView animateWithDuration:0.2f delay:0 options:UIViewAnimationOptionTransitionNone animations:^{
            _viewIndicator.left = targetX;
        } completion:nil];
    }
    
    // label color
    if ([AppUtils isEmptyArray:_tabLabels] || index > _tabLabels.count) {
        return;
    }
    
    if (![_tabLabels[index] isKindOfClass:[UILabel class]]) {
        return;
    }
    
    // new selection
    UILabel *newLabel = _tabLabels[index];
    [self updateLabelFont:newLabel selected:YES];
    
    // old selection
    if (oldSelect >= 0 && oldSelect < _tabLabels.count && [_tabLabels[oldSelect] isKindOfClass:[UILabel class]]) {
        UILabel *oldLabel = _tabLabels[oldSelect];
        [self updateLabelFont:oldLabel selected:NO];
    }
}

- (void)updateLabelFont:(UILabel *)label selected:(BOOL)selected
{
    if (nil == label) {
        return;
    }
    
    if (selected) {
        if (nil != _selColor) {
            [label setTextColor:_selColor];
        }
        if (nil != _font) {
            UIFont *boldFont = [UIFont boldSystemFontOfSize:[_font pointSize]];
            [label setFont:boldFont];
        }
    }
    else {
        if (nil != _unselColor) {
            [label setTextColor:_unselColor];
        }
        if (nil != _font) {
            UIFont *sysFont = [UIFont systemFontOfSize:[_font pointSize]];
            [label setFont:sysFont];
        }
    }
}

- (void)setRedPoint:(NSInteger)num index:(NSInteger)index
{
    if (index < 0 || index >= _tabCount) {
        return;
    }
    UIView *view = _tabPointViews[index];
    UILabel *label = _tabPointLabels[index];
    if (num <= 0) {
        [view setHidden:YES];
        return;
    }
    [view setHidden:NO];
    [label setText:[NSString stringWithFormat:@"%zd", num]];
}

- (void)setSelectionChangeHandler:(id)target action:(SEL)action
{
    _target = target;
    _select = action;
}

#pragma mark --UICollectionViewDelegateFlowLayout
- (CGSize)collectionView:(UICollectionView *)collectionView layout:(UICollectionViewLayout*)collectionViewLayout sizeForItemAtIndexPath:(NSIndexPath *)indexPath
{
    return CGSizeMake(_frameWidth / (CGFloat)_tabCount, _collectionTypeSelect.height);
}

-(UIEdgeInsets)collectionView:(UICollectionView *)collectionView layout:(UICollectionViewLayout *)collectionViewLayout insetForSectionAtIndex:(NSInteger)section
{
    return UIEdgeInsetsMake(0, 0, 0, 0);
}

#pragma mark --UICollectionViewDataSource
- (NSInteger)collectionView:(UICollectionView *)collectionView numberOfItemsInSection:(NSInteger)section
{
    return 1;
}

- (NSInteger)numberOfSectionsInCollectionView:(UICollectionView *)collectionView
{
    return _tabCount;
}

- (UICollectionViewCell *)collectionView:(UICollectionView *)collectionView cellForItemAtIndexPath:(NSIndexPath *)indexPath
{
    UICollectionViewCell *cell = [_collectionTypeSelect dequeueReusableCellWithReuseIdentifier:s_tabViewCellIdentifier forIndexPath:indexPath];
    if (nil == cell) {
        return cell;
    }
    
    for (UIView *child in [cell subviews]) {
        [child removeFromSuperview];
    }
    
    UILabel *label = [[UILabel alloc] initWithFrame:CGRectMake(0, 0, _frameWidth / (CGFloat)_tabCount, _collectionTypeSelect.height)];
    
    // font
    if (nil != _font) {
        [label setFont:_font];
    }
    
    // alignment
    [label setTextAlignment:NSTextAlignmentCenter];
    
    // text
    if (![AppUtils isEmptyArray:_titles] && indexPath.section < _titles.count) {
        [label setText:_titles[indexPath.section]];
    }
    
    // font color
    if (indexPath.section == _selIndex) {
        [self updateLabelFont:label selected:YES];
    }
    else {
        [self updateLabelFont:label selected:NO];
    }
    
    // seperator
    if (_showSeperator && indexPath.section > 0) {
        UIView *line = [[UIView alloc] initWithFrame:CGRectMake(0, 0, 0.5, _collectionTypeSelect.height)];
        [line setBackgroundColor:[UIColor colorWithString:COLOR_DBD9DE]];
        [label addSubview:line];
    }
    
    // red point
    CGFloat x = _frameWidth / _tabCount * _redPointOffset;
    UIView *pointView = [[UIView alloc] initWithFrame:CGRectMake(x, 10, 14, 14)];
    [pointView.layer setMasksToBounds:YES];
    [pointView.layer setCornerRadius:7];
    [pointView setBackgroundColor:[UIColor redColor]];
    [pointView setHidden:YES];
    
    UILabel *labelPoint = [[UILabel alloc] initWithFrame:CGRectMake(0, 0, 14, 14)];
    [labelPoint setFont:[UIFont systemFontOfSize:9]];
    [labelPoint setTextAlignment:NSTextAlignmentCenter];
    [labelPoint setTextColor:[UIColor whiteColor]];
    [pointView addSubview:labelPoint];
    
    [label addSubview:pointView];
        
    // store in _tabLabels
    if (indexPath.section < _tabCount) {
        _tabLabels[indexPath.section] = label;
        _tabPointViews[indexPath.section] = pointView;
        _tabPointLabels[indexPath.section] = labelPoint;
    }
    [cell addSubview:label];
    return cell;
}

#pragma mark --UICollectionViewDelegate
- (void)collectionView:(UICollectionView *)collectionView didSelectItemAtIndexPath:(NSIndexPath *)indexPath
{
    [self selectIndex:indexPath.section];
    
    if (nil != _target && nil != _select) {
        [_target performSelectorOnMainThread:_select withObject:[NSNumber numberWithInteger:indexPath.section] waitUntilDone:YES];
    }
}

- (BOOL)collectionView:(UICollectionView *)collectionView shouldSelectItemAtIndexPath:(NSIndexPath *)indexPath
{
    return YES;
}

@end
